package com.mrx.agent.util;

import java.lang.reflect.InvocationTargetException;

/**
 * @author Mr.X
 * @since 2024-11-05 15:20
 **/
public class ReflectionUtils {

    public static Object newInstance(Class<?> clazz) {
        try {
            return clazz.getDeclaredConstructor().newInstance();
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException |
                 NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }

    public static Object invokeMethod(String method, Object arg, Object instance, Class<?>... paramTypes) {
        return invokeMethod(method, arg, instance.getClass(), instance, paramTypes);
    }

    public static Object invokeMethod(String method, Object arg, Class<?> clazz, Class<?>... paramTypes) {
        return invokeMethod(method, arg, clazz, null, paramTypes);
    }

    public static Object invokeMethod(String method, Object arg, Class<?> clazz, Object instance, Class<?>... paramTypes) {
        try {
            return clazz.getDeclaredMethod(method, paramTypes).invoke(instance, arg);
        } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }

}
